package pri.hillchen.std.concurrent.chapter5.util;

import java.util.concurrent.CountDownLatch;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 8:20 2018/2/8 0008.
 */
public class TestHarness {
    public long timeTasks(final Runnable[] tasks) throws InterruptedException {
        if(tasks == null || tasks.length == 0){
            return  0;
        }
        final CountDownLatch startLatch = new CountDownLatch(1);
        final CountDownLatch endLatch = new CountDownLatch(tasks.length);
        for(final Runnable runnable : tasks){
            new Thread(){
                @Override
                public void run() {
                    try {
                        startLatch.await();
                        try{
                            runnable.run();
                        }finally {
                            endLatch.countDown();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        long startTime = System.nanoTime();
        startLatch.countDown();
        endLatch.await();
        long endTime = System.nanoTime();
        return endTime - startTime;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable[] runnables = new Runnable[10];
        for(int i=0;i<10;i++){
            final int threadId = i;
            runnables[threadId] = new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(500);
                        System.out.println(threadId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
        }
        System.out.println(new TestHarness().timeTasks(runnables));
    }

}
